package controller

import (
	"bytes"
	"context"
	"github.com/gin-gonic/gin"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"io"
	"log"
	"net/http"
	"web-tools-go/define"
	"web-tools-go/utils"
)

func FileUpload(c *gin.Context) {
	buf := bytes.NewBuffer(nil)
	file, _, err := c.Request.FormFile("file")
	if err != nil {
		log.Printf("FileUpload Error:%v \n", err)
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "文件上传失败" + err.Error(),
		})
		return
	}
	io.Copy(buf, file)
	data := buf.Bytes()
	key := "img/qrcode-logo/" + utils.GetRand25()
	putPolicy := storage.PutPolicy{
		Scope: define.Bucket,
	}
	mac := qbox.NewMac(define.AccessKey, define.SecretKey)
	upToken := putPolicy.UploadToken(mac)
	cfg := storage.Config{}
	// 空间对应的机房
	cfg.Zone = &storage.ZoneHuanan
	// 是否使用https域名
	cfg.UseHTTPS = true
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = false
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	putExtra := storage.PutExtra{
		Params: map[string]string{
			"x:name": "github logo",
		},
	}
	dataLen := int64(len(data))
	err = formUploader.Put(context.Background(), &ret, upToken, key, bytes.NewReader(data), dataLen, &putExtra)
	if err != nil {
		log.Printf("formUploader Error:%v \n", err)
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"msg":  "文件上传失败" + err.Error(),
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 1,
		"url":  define.UrlAddress + key,
	})
}
